package com.example.othree.util;


import com.example.othree.entity.StationData;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

// 请求天擎接口工具类
public class TianQinUtils {
    private static final String SERVICE_NODE_ID = "NMIC_MUSIC_CMADAAS";
    private static final String SERVICE_IP = "10.48.90.120:80";
    private static final String USER_ID = "HBHS_HANBING";
    private static final String PASSWORD = "Hanbing@0124";
    private static final String DATA_FORMAT = "json";
    private static final String INTERFACE_ID = "getSurfEleByTimeRange";
    private static final String DATA_CODE = "SURF_CHN_MUL_DAY";
    private static final String ELEMENTS = "Station_Id_C,Lat,Lon,City,Station_Name,Cnty,Province,Datetime,PRS_Avg,PRS_Max,PRS_Min,TEM_Max,TEM_Avg,TEM_Min,RHU_Avg,RHU_Min,PRE_Time_2020,PRE_Time_0808,WIN_S,WIN_S_2mi_Avg,GST_Avg,GST_Max,GST_Min,SSH";
    private static final String ELE_VALUE_RANGES = "City: '衡水市', '邢台市'";
    private static final String ORDER_BY = "Station_Id_C,Datetime";

    // 保存字符串到文件的方法

    public static String getAirJson(String timeRange) throws Exception {
        String baseUrl = "http://" + SERVICE_IP + "/music-ws/api?serviceNodeId=" + SERVICE_NODE_ID
                + "&userId=" + USER_ID + "&interfaceId=" + INTERFACE_ID + "&dataCode=" + DATA_CODE
                + "&elements=" + ELEMENTS + "&timeRange=" + timeRange + "&eleValueRanges=" + ELE_VALUE_RANGES
                + "&orderBy=" + ORDER_BY + "&dataFormat=" + DATA_FORMAT;

        // 生成时间戳和UUID
        String timestamp = String.valueOf(System.currentTimeMillis());
        String nonce = UUID.randomUUID().toString();

        baseUrl += "&timestamp=" + timestamp + "&nonce=" + nonce;

        // 生成sign
        Map<String, String> signParams = new HashMap<>();
        signParams.put("serviceNodeId", SERVICE_NODE_ID);
        signParams.put("userId", USER_ID);
        signParams.put("interfaceId", INTERFACE_ID);
        signParams.put("dataCode", DATA_CODE);
        signParams.put("elements", ELEMENTS);
        signParams.put("timeRange", timeRange);
        signParams.put("eleValueRanges", ELE_VALUE_RANGES);
        signParams.put("dataFormat", DATA_FORMAT);
        signParams.put("timestamp", timestamp);
        signParams.put("orderBy", ORDER_BY);
        signParams.put("nonce", nonce);
        signParams.put("pwd", PASSWORD);

        String sign = getSign(signParams);
        if (sign.isEmpty()) {
            System.out.println("generate sign is None");
            return null;
        }
        baseUrl += "&sign=" + sign;

        // 发起请求并获取返回的JSON数据
        return sendHttpRequest(baseUrl);
    }

    public static String getSign(Map<String, String> signParams) {
        StringBuilder paramString = new StringBuilder();
        signParams.keySet().stream().sorted().forEach(key -> {
            paramString.append(key).append("=").append(signParams.get(key)).append("&");
        });

        if (paramString.length() > 0) {
            paramString.setLength(paramString.length() - 1);  // 移除最后的&符号
        }

        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(paramString.toString().getBytes(StandardCharsets.UTF_8));
            byte[] digest = md.digest();
            StringBuilder hexString = new StringBuilder();
            for (byte b : digest) {
                hexString.append(String.format("%02x", b));
            }
            return hexString.toString().toUpperCase();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public static String sendHttpRequest(String requestUrl) throws Exception {
//        String encodedURL=java.net.URLEncoder.encode(requestUrl,"UTF-8");
        URL url = new URL(requestUrl.replace(" ", "%20"));
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        // Get response
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder response = new StringBuilder();
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        return response.toString();
    }

    public static List<StationData> getData(String startTime, String endTime) {
        // "[20151010000000,20151204000000]"
        String timeRange = "["+startTime+","+endTime+"]";
        try {
            String jsonResponse = getAirJson(timeRange);
            try {
                // 解析 JSON 字符串
                ObjectMapper objectMapper = new ObjectMapper();
                // 解析 "DS" 部分为 List<StationData>
                JsonNode dsNode = objectMapper.readTree(jsonResponse).path("DS");
                return objectMapper.readValue(
                        dsNode.toString(), objectMapper.getTypeFactory().constructCollectionType(List.class, StationData.class)
                );

            } catch (Exception e) {
                e.printStackTrace();
            }


        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

}
